package logic

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"pharymacy-management-system/dao/mysql"
	"pharymacy-management-system/models"
	"pharymacy-management-system/network"
	"pharymacy-management-system/pkg/jwt"
	"pharymacy-management-system/pkg/snowflake"
	"strconv"
)

func SignUp(p *models.ParamSignUp) (err error) {
	// 判断用户是否存在
	if err = mysql.CheckUserExist(p.Username); err != nil {
		return
	}
	// 生成UUID
	userID := snowflake.GenID()
	// 构造user实例
	user := models.User{
		UserID:   userID,
		Username: p.Username,
		Password: p.Password,
	}
	// 保存进数据库
	return mysql.InsertUser(&user)
}

func Login(p *models.ParamLogin) (string, error) {
	// 判断用户是否存在
	user := &models.User{
		Username: p.Username,
		Password: p.Password,
	}
	// 验证用户
	err := mysql.Login(user)
	if err != nil {
		return "", err
	}
	return jwt.GenToken(user.UserID, user.Username)
}

func GetUserByUserID(userID int64) (user *models.User, err error) {
	user, err = mysql.SelectUserByUserID(userID)
	if user == nil {
		return
	}
	user.Password = ""
	err = nil
	return
}

func UpdateUserNickName(user *models.User) (err error) {
	return mysql.UpdateUserNickNameByUserID(user)
}

func GetUserList(c *gin.Context) {
	userList, err := mysql.SelectAllUser()
	if err != nil {
		zap.L().Error("mysql.SelectAllUser failed", zap.Error(err))
		network.ResponseError(c, network.CodeServerBusy)
		return
	}

	// 定义一个可以放任何类型的列表
	tempList := make([]interface{}, 0)
	for i := range userList {
		tempData := make(map[string]string)
		tempValue := strconv.FormatInt(userList[i].UserID, 10)
		tempText := userList[i].UserNickName

		tempData["value"] = tempValue
		tempData["text"] = tempText

		tempList = append(tempList, tempData)
	}
	data := map[string]interface{}{}
	data["userList"] = tempList
	network.ResponseSuccess(c, data)
}

func GetAllUser(c *gin.Context) {
	userList, err := mysql.SelectAllUser()
	if err != nil {
		zap.L().Error("mysql.SelectAllUser failed", zap.Error(err))
		network.ResponseError(c, network.CodeServerBusy)
		return
	}
	data := map[string]interface{}{}
	data["userList"] = userList
	network.ResponseSuccess(c, data)
}

func DeleteUser(c *gin.Context) {
	var userID int64
	userID, err := strconv.ParseInt(c.Param("user_id"), 10, 64)
	if err != nil {
		zap.L().Error("strconv.ParseInt(c.Param(\"user_id\")) failed", zap.Error(err))
		network.ResponseError(c, network.CodeInvalidParam)
		return
	}

	err = mysql.DeleteUserByUserID(userID)
}
